package com.common.frame.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.text.TextUtils
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.common.frame.R

class NoPaddingTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private val rect = Rect()

    var isMedium = false

    init {
        val arr = context.obtainStyledAttributes(attrs, R.styleable.NoPaddingTextView)
        isMedium = arr.getBoolean(R.styleable.NoPaddingTextView_isMedium, false)
        arr.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val specModeW = MeasureSpec.getMode(widthMeasureSpec)
        val specModeH = MeasureSpec.getMode(heightMeasureSpec)
        calculateTextParams()
        if (specModeW == MeasureSpec.AT_MOST && specModeH == MeasureSpec.AT_MOST) {
            setMeasuredDimension(rect.right - rect.left, -rect.top + rect.bottom)
        }
    }

    override fun onDraw(canvas: Canvas?) {
        if (isMedium) {
            paint.strokeWidth = 0.9F
        }
        drawText(canvas)
    }

    private fun calculateTextParams(): String {
        var text = text.toString()
        if (TextUtils.isEmpty(text)) {
            text = ""
        }
        val textLength = text.length
        paint.getTextBounds(text, 0, textLength, rect)
        if (textLength == 0) {
            rect.right = rect.left
        }
        return text
    }

    private fun drawText(canvas: Canvas?) {
        val text = calculateTextParams()
        val left = rect.left
        val bottom = rect.bottom
        val x = (width - (rect.right - rect.left)) / 2f
        val y = (height - (-rect.top + rect.bottom)) / 2f
        rect.offset(-rect.left, -rect.top)
        paint.isAntiAlias = true
        paint.color = currentTextColor
        paint.typeface = typeface
        canvas?.drawText(text, (-left).toFloat() + x, (rect.bottom - bottom).toFloat() + y, paint)
    }

}
